<template>
  <view class="benben-image-upload" @click="clickEvent">
    <slot />
  </view>
</template>
<script>
  import {
    UploadImage
  } from '@/common/utils/index'
  /*  @property  {String} imgiId            图片id    选填填项
      @property  {String} path            图片路径    必填项
      @property  {Boolean} isCropping     是否开启裁剪模式   false
      @property  {Boolean} isShowClean     是否显示删除图标   false
  		@property  {function} update-success  上传成功回调
      */
  // isShowClean 为true 时  slot 中必须有一个data-type="clean"的 text 标签
  // <text  data-type="clean" class='fu-iconfont2 position-absolute'>&#xE8E7;</text>
  export default {
    name: 'benben-image-upload',
    props: {
      isShowClean: {
        type: [Boolean],
        default: false,
      },
      isCropping: {
        type: [Boolean],
        default: false,
      },
      uploadLoading: {
        type: [Boolean],
        default: false,
      },
      path: {
        type: String,
        default: '',
      },
      imgiId: {
        type: [String, Number],
        default: '',
      },
    },
    data: () => ({
      uploading: false,
    }),
    computed: {},
    //监听imgIds
    watch: {},
    methods: {
      clickEvent(e) {
        // #ifndef MP-WEIXIN
        if (this.isShowClean && e.target.dataset.type == 'clean') {
          this.$emit('update:img-id', '')
          this.$emit('update:path', '')
          return
        }
        // #endif
        // #ifdef MP-WEIXIN
        if (this.isShowClean && e._relatedInfo.anchorTargetText) {
          this.$emit('update:img-id', '')
          this.$emit('update:path', '')
          return
        }
        // #endif
        if (this.isShowClean && this.path) {
          uni.previewImage({
            current: this.path,
            urls: [this.path],
          })
          return
        }
        if (!this.isCropping) this.soloChooseImage()
        else this.croppingUploadImage()
      },
      UploadImage(tempFiles) {
        this.$emit('update:upload-loading', true)
        // 开始上传
        this.uploading = true
        new UploadImage(tempFiles, {
          complete: (res) => {
            this.uploading = false
            this.$emit('update:img-id', res[0].id)
            this.$emit('update:path', res[0].path)
            this.$emit('update:upload-loading', false)
            this.$emit('update-success', res[0])
          },
        })
      },
      soloChooseImage() {
        if (this.uploading) return
        let platform = uni.getSystemInfoSync().platform
        if (platform != 'ios') {
          this.soloChooseImage1()
          return
        }
        // 从相册中选择图片
        uni.chooseImage({
          count: 1, // 默认3
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          success: (res) => this.UploadImage(res.tempFiles),
        })
      },
      soloChooseImage1() {
        let self = this
        if (self.uploading) return
        uni.showModal({
          title: '相机相册信息授权提示',
          content: '用户拍摄/选取内容发布，拍摄/选取图片更换头像，扫描二维码，聊天功能，提交意见反馈或者AR识别等功能？',
          success(res1) {
            if (res1.confirm) {
              // 从相册中选择图片
              uni.chooseImage({
                count: 1, // 默认3
                sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                success: (res) => self.UploadImage(res.tempFiles),
              })
            } else if (res1.cancel) {
              console.log('用户点击取消');
            }
          }
        })
      },
      imageCroppingCuccess() {
        uni.$once('image-cropping-success', (file) => {
          if (!file) return
          this.UploadImage([file])
        })
      },
      //裁剪图片上传
      croppingUploadImage(id, path, obj, obj1, fnName = false) {
        let self = this
        let platform = uni.getSystemInfoSync().platform
        console.log('croppingUploadImage1', platform)
        if (platform != 'ios') {
          self.croppingUploadImage1(id, path, obj, obj1, fnName = false)
          return
        }
        let itemList = self.path ? [global.i18n.t('修改头像'), global.i18n.t('拍照'), global.i18n.t('从手机相册选择')] : [global.i18n
          .t('拍照'), global.i18n.t('从手机相册选择')
        ]
        uni.showActionSheet({
          itemList: itemList,
          success: (res) => {
            if (res.tapIndex == 0 && self.path) {
              uni.navigateTo({
                url: '/pages/benben-built-in/image-cropping/image-cropping?rectHeight=200&rectWidth=200&&myImgUrl=' +
                  self.path,
                animationDuration: 0,
              })
              self.imageCroppingCuccess()
            }
            if ((res.tapIndex == 1 && self.path) || (res.tapIndex == 0 && !self.path)) {
              uni.chooseImage({
                count: 1,
                sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
                success: (res) => {
                  // 跳转到图片裁切页面
                  uni.navigateTo({
                    url: `/pages/benben-built-in/image-cropping/image-cropping?rectHeight=200&rectWidth=200&fileType=${res.tempFiles[0].type}&myImgUrl=${res.tempFilePaths[0]}`,
                    animationDuration: 0,
                  })
                  self.imageCroppingCuccess()
                },
              })
            }
            if ((res.tapIndex == 2 && self.path) || (res.tapIndex == 1 && !self.path)) {
              uni.chooseImage({
                count: 1,
                sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有
                success: (res) => {
                  // 跳转到图片裁切页面
                  uni.navigateTo({
                    url: `/pages/benben-built-in/image-cropping/image-cropping?rectHeight=200&rectWidth=200&fileType=${res.tempFiles[0].type}&myImgUrl=${res.tempFilePaths[0]}`,
                    animationDuration: 0,
                  })
                  self.imageCroppingCuccess()
                },
              })
            }
          },
          fail: function(res) {
            console.log(res.errMsg)
          },
        })
      },
      croppingUploadImage1(id, path, obj, obj1, fnName = false) {
        let self = this
        let itemList = self.path ? [global.i18n.t('修改头像'), global.i18n.t('拍照'), global.i18n.t('从手机相册选择')] : [
          global.i18n.t('拍照'), global.i18n.t('从手机相册选择')
        ]
        uni.showModal({
          title: '相机相册信息授权提示',
          content: '用户拍摄/选取内容发布，拍摄/选取图片更换头像，扫描二维码，聊天功能，提交意见反馈或者AR识别等功能？',
          success(res1) {
            if (res1.confirm) {

              uni.showActionSheet({
                itemList: itemList,
                success: (res) => {
                  if (res.tapIndex == 0 && self.path) {
                    uni.navigateTo({
                      url: '/pages/benben-built-in/image-cropping/image-cropping?rectHeight=200&rectWidth=200&&myImgUrl=' +
                        self.path,
                      animationDuration: 0,
                    })
                    self.imageCroppingCuccess()
                  }
                  if ((res.tapIndex == 1 && self.path) || (res.tapIndex == 0 && !self.path)) {
                    uni.chooseImage({
                      count: 1,
                      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                      sourceType: ['camera'], // 可以指定来源是相册还是相机，默认二者都有
                      success: (res) => {
                        // 跳转到图片裁切页面
                        uni.navigateTo({
                          url: `/pages/benben-built-in/image-cropping/image-cropping?rectHeight=200&rectWidth=200&fileType=${res.tempFiles[0].type}&myImgUrl=${res.tempFilePaths[0]}`,
                          animationDuration: 0,
                        })
                        self.imageCroppingCuccess()
                      },
                    })
                  }
                  if ((res.tapIndex == 2 && self.path) || (res.tapIndex == 1 && !self.path)) {
                    uni.chooseImage({
                      count: 1,
                      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                      sourceType: ['album'], // 可以指定来源是相册还是相机，默认二者都有
                      success: (res) => {
                        // 跳转到图片裁切页面
                        uni.navigateTo({
                          url: `/pages/benben-built-in/image-cropping/image-cropping?rectHeight=200&rectWidth=200&fileType=${res.tempFiles[0].type}&myImgUrl=${res.tempFilePaths[0]}`,
                          animationDuration: 0,
                        })
                        self.imageCroppingCuccess()
                      },
                    })
                  }
                },
                fail: function(res) {
                  console.log(res.errMsg)
                },
              })
            } else if (res1.cancel) {
              console.log('用户点击取消');
            }
          }
        })

      },
    },
    // 组件周期函数--监听组件挂载完毕
    mounted() {},
    // 组件周期函数--监听组件数据更新之前
    beforeUpdate() {},
    // 组件周期函数--监听组件数据更新之后
    updated() {},
    // 组件周期函数--监听组件激活(显示)
    activated() {},
    // 组件周期函数--监听组件停用(隐藏)
    deactivated() {},
    // 组件周期函数--监听组件销毁之前
    beforeDestroy() {},
  }
</script>
<style lang="scss">
  .benben-image-upload {
    line-height: initial;
  }
</style>
